package plugin.live.redis;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

import lombok.Data;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
@RequiredArgsConstructor
public class RedisObjByteMap<T> {
	private Cache use = Redis.use();
	private @NonNull String cacheName;

	public long delAll() {
		Long del = use.del(cacheName);
		return del;
	}

	public long del(String... fields) {
		return use.hdel(cacheName, fields);
	}

	public long put(String field, T t) {
		return use.hset(cacheName, field, this.getByte(t));
	}

	public Map<String, T> getMap() {
		Map<String, T> mapTem = new HashMap<String, T>();
//		log.info("use:"+use);
//		if(use == null) {
//			return null;
//		}
//		log.info("cacheName:"+cacheName);
		Map<String, Object> map = use.hgetAll(cacheName);
		
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next().toString();
			T t = (T) this.getObj((byte[]) map.get(key));
			mapTem.put(key, t);
		}
		return mapTem;
	}
	
	public T getMapBySubKey(String subKey) {
		T t = (T) this.getObj((byte[]) use.hget(cacheName, subKey));
		return t;
	}

	private byte[] getByte(T t) {
		return SerializeUtil.serialize(t);
	}

	@SuppressWarnings("unchecked")
	private T getObj(byte[] bytes) {
		return (T) SerializeUtil.unserialize(bytes);
	}
}
